package model;


import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.widgets.Display;
import mapproviderapi.MapTile;


public class MapTileImage implements Runnable {
	private Bound2D bound;
	
	private ImageData imageData = null;
	
	private String tileUrl;
	
	public MapTileImage(MapTile mapTile){
		bound = new Bound2D(mapTile.getTop(), mapTile.getLeft(), mapTile.getTileWidth(), mapTile.getTileHeight());
		tileUrl = mapTile.getTileUrl();
	}

	@Override
	public void run() {
		InputStream ip = null;
		try {			
			URLConnection httpConnection = (new URL(tileUrl)).openConnection();
			ip = httpConnection.getInputStream();
			imageData = new ImageData(ip);
		} catch (MalformedURLException e) {			
			e.printStackTrace();
		} catch (IOException e) {			
			e.printStackTrace();
		} finally{
			if (ip != null){
				try {
					ip.close();
				} catch (IOException e) {					
					e.printStackTrace();
				}
			}
		}
	}
	
	public Image getImage(Display display){
		if (imageData == null){
			return null;
		}
		return new Image(display, imageData);
	}
	
	public Bound2D getBound(){
		return bound;
	}
}
